package com.foodcommunity.controller;

import com.foodcommunity.common.Result;
import com.foodcommunity.entity.FoodPost;
import com.foodcommunity.entity.User;
import com.foodcommunity.service.FoodPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/posts")
public class PostApiController {

    @Autowired
    private FoodPostService foodPostService;

    @DeleteMapping("/{id}")
    public Result<Void> deletePost(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("未登录");
        }
        return foodPostService.deletePost(id, user.getId());
    }

    @GetMapping("/{id}")
    public Result<FoodPost> getPostDetail(@PathVariable Long id) {
        return foodPostService.getPostDetail(id);
    }

    @PostMapping
    public Result<FoodPost> createPost(@RequestBody FoodPost post, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("未登录");
        }
        post.setUserId(user.getId());
        return foodPostService.createPost(post);
    }

    @PutMapping("/{id}")
    public Result<FoodPost> updatePost(@PathVariable Long id, @RequestBody FoodPost post, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("未登录");
        }
        post.setId(id);
        post.setUserId(user.getId());
        return foodPostService.updatePost(post);
    }
    
    /**
     * 点赞功能
     */
    @PostMapping("/{id}/like")
    public Result<Integer> likePost(@PathVariable Long id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        return foodPostService.likePost(id, user.getId());
    }
} 